<?php

namespace App\ServicesNew;

trait BaseSearchServiceTrait
{
    private static $DEFAULT_PAGE_SIZE = 10;

    private static $MAX_PAGE_SIZE = 50;  // 默认一次最多返回五十条数据

    /**
     * @param string $entity
     * @param string $model
     * @param $searchInfo
     * @param \Closure|null $getSearchCondition
     * @return array
     */
    protected function getEntities(string $entity, string $model, $searchInfo, \Closure $getSearchCondition = null)
    {
        $page = $searchInfo->getPage();
        $pageSize = min($searchInfo->getPageSize() ?: self::$DEFAULT_PAGE_SIZE, self::$MAX_PAGE_SIZE);
        $searchInfo->setPageSize($pageSize);

        if ($getSearchCondition instanceof \Closure) {
            $condition = $getSearchCondition($searchInfo);
        } else {
            $condition = $this->getSearchCondition($searchInfo);
        }

        $collection = $model::where($condition)
            ->offset(($page - 1) * $pageSize)
            ->limit($pageSize)
            ->orderByRaw($searchInfo->getOrderByRaw())
            ->get();

        $data = [];
        foreach ($collection as $label) {
            $data[] = new $entity($label);
        }

        return $data;
    }

    /**
     * @param string $model
     * @param $searchInfo
     * @return mixed
     */
    protected function countNum(string $model, $searchInfo)
    {
        return $model::where($this->getSearchCondition($searchInfo))->count();
    }
}
